package com.devunion.bogdan.view.project.actions;

import com.devunion.bogdan.model.project.*;
import com.devunion.bogdan.model.UserManager;
import com.devunion.bogdan.view.project.PaperNode;
import com.devunion.bogdan.view.LibrarianEditor;
import com.devunion.bogdan.io.DataSourceProvider;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.*;

/**
 * @author Viktar Liaskovich
 */
public class AddPageAction extends AbstractProjectAction {
    public boolean isApplicable(Paper e) {
        final User u = UserManager.getInstance().getUser();

        if (u == null || u.isNormal()) {
            return false;
        }

        final Project p = ProjectManager.getInstance().getCurrentProject();

        return u.isAdmin() || u.isExpert() && u.getLogin().equals(p.getOwner().getLogin());
    }

    public void actionPerformed(ActionEvent e) {

        final JTree projectTree = LibrarianEditor.getInstance().getSelectedWorkspace().getProjectTreeBrowser().getProjectTree();
        PaperNode selectedNode = (PaperNode) projectTree.getSelectionPath().getLastPathComponent();

        Paper paper = selectedNode.getUserObject();

        Page lastPage = paper.getLastPage();

        if (lastPage == null) {
            Page page = createPage(1);

            if (page != null) {
                paper.addPage(page);
            }
        } else {
            Page page = createPage(lastPage.getPageNumber() + 1);

            if (page != null) {
                paper.addPage(page);
            }
        }
    }

    private Page createPage(int number) {
        Image image = DataSourceProvider.getInstance().getDataSource().asquireImage();

        if (image == null) {
            return null;
        }

        Page page = new Page(number);
        page.setImageObject(image);

        return page;
    }
}
